<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1" import="java.security.MessageDigest"
	import="beans.Query1" import="java.sql.*" import="java.util.Enumeration" import="java.util.ArrayList"%>
<jsp:useBean id="dbConn" scope="session" class="beans.Query1" />
<jsp:useBean id="sender" scope="session" class="beans.SendEmail" />
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Dovrei.it | Report</title>
<script src="../js/jquery.min.js"></script>
<script src="../js/jquery.ui.core.js"></script>
<script src="../js/jquery.ui.widget.js"></script>
<script src="../js/jquery.ui.datepicker.js"></script>
<script src="../js/jquery.ui.position.js"></script>
<script src="../js/jquery.ui.autocomplete.js"></script>
<style type="text/css" title="currentStyle">
@import "../css/jquery-ui-1.8.16.custom.css";

@import "../css/demos.css";

@import url(http://fonts.googleapis.com/css?family=Montez);
</style>
<style>
.ui-autocomplete-loading {
	background: white url('../images/ui-anim_basic_16x16.gif') right center
		no-repeat;
}

.ui-datepicker-title:hover {
	cursor: pointer;
}
</style>
<script type="text/javascript" language="javascript" src="../js/home.js"></script>
</head>
<body>
	<%!
private Connection conn;
private String user="";
private String userId="";

private boolean checkLogin(String username, String password){
	if (username == null || password == null) {
		return false;
	} else if (checkUserAndPass(username, password)){
		return true;
	}
	return false;
}

private boolean checkUserAndPass(String username, String password){
	try{
		ResultSet rs= null;
		PreparedStatement pSt= null;
		String query="select * from utenti where username=? and password=md5(?) and reg_status='ACCEPTED'";
		pSt = conn.prepareStatement(query);	
		pSt.setString(1,username);
		pSt.setString(2,password);
		rs=pSt.executeQuery();
		if(rs.next()){
			user=(rs.getString("nome")+" "+rs.getString("cognome"));
			userId=rs.getString("userId");
			return true;
		}
		rs.close();
	} catch (Exception e){
		e.printStackTrace();
	}
	return false;
	/*if((username.toLowerCase().trim().equals("admin"))
		&&
	   (password.toLowerCase().trim().equals("admin")))
		return true;
	else
		return false;*/
}

%>
	<table width=100% border="0">
		<tr>
			<td width=15% rowspan="2" valign="bottom"><img
				src="../IMG/ominosx_m.gif" alt="last minute sx" align="right" /></td>
			<td width=70% height="150">
				<table width=100% height=100% border="0">
					<tr height=15%>
						<td>Tutte le migliori offerte on-line per viaggiare.</td>
					</tr>
					<tr height=35%>
						<td></td>
					</tr>
					<tr height=50%>
						<td><a href="index.jsp"
							style="text-decoration: none; color: #000000"><img
								src="../IMG/logo_mini.gif" alt="dovrei partire logo" height="75"
								style="vertical-align: bottom" /><font FACE="Montez" size="22">
									Dovrei... Report!</font></a></td>
					</tr>
				</table>
			</td>
			<td width=15% rowspan="2" valign="middle"><img
				src="../IMG/ominodx_m.gif" alt="last minute dx" align="left" /></td>
		</tr>
		<tr>
			<td><BR> <BR> <% 
		conn = dbConn.getConn();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		if(username==null && password==null){
		}else{
			if(checkLogin(username, password)){
				session.setAttribute("userId", userId);
				session.setAttribute("user", user);
			} else {
				%> <font color="red" style="margin-left: 12%"> Username o
					password errati </font> <%
			}
		}
		
		if (session.getAttribute("userId")==null) {
			//Se username o password nulle visualizzo il form di accesso
			%>
				<form method="post" action="index.jsp" id="formlogin"
					style="margin-left: 12%">
					<table>
						<tr>
							<td>Username :</td>
							<td><input name="username" size=15 type="text" /></td>
						</tr>
						<tr>
							<td>Password :</td>
							<td><input name="password" size=15 type="password" /></td>
						</tr>
					</table>
					<input type="submit" value="Login" /> <BR> <a
						href="register.jsp">Non sei registrato? Clicca qui</a>
				</form> <%
		//Se il login ha successo visualizzo i link ai report
		} else {
			user=(String) session.getAttribute("user");
			userId=(String) session.getAttribute("userId");
			%>
				<h2>
					Benvenuto
					<%=user%></h2> Ecco la lista dei report disponibili <br> <br>
				<a href="report.jsp?query=prezzo_medio">Prezzo medio dei voli</a> <BR>
				<a href="report.jsp?query=voli_giorno">Voli acquistati per
					giorno</a> <%
			//Parte riservata all'amministratore
			if(userId.equals("13")){
				if(request.getParameter("submitted")!=null){
					ResultSet rs= null;
					PreparedStatement pSt= null;
					String acceptQuery = "update utenti set reg_status='ACCEPTED' where userId in(";
					String refuseQuery = "delete from utenti where userId in (";
					Enumeration<String> parEnum = request.getParameterNames();
					ArrayList<String> acceptUsers = new ArrayList<String>();
					ArrayList<String> refuseUsers = new ArrayList<String>();
					while(parEnum.hasMoreElements()){
						String par = parEnum.nextElement();
						if(par.startsWith("status")){
							if(request.getParameter(par).equals("accept"))
								acceptUsers.add(par.replace("status", ""));
							else 
								refuseUsers.add(par.replace("status", ""));
						}
						
					}
					//Mail di accettazione o rifiuto
					sender.sendEmail(acceptUsers, refuseUsers);
					//Update utenti accettati
					for(String userId : acceptUsers){
						acceptQuery+="'"+userId+"',";
					}
					acceptQuery+="'')";
					acceptQuery=acceptQuery.replace(",'')", ")");
					//Delete utenti rifiutati
					for(String userId : refuseUsers){
						refuseQuery+="'"+userId+"',";
					}
					refuseQuery+="'')";
					refuseQuery=refuseQuery.replace(",'')", ")");
					
					try{
						pSt = conn.prepareStatement(acceptQuery);	
						pSt.executeUpdate();
						pSt = conn.prepareStatement(refuseQuery);	
						pSt.executeUpdate();
					} catch (Exception e){
						e.printStackTrace();
					}
				} else {
					try{
						ResultSet rs= null;
						PreparedStatement pSt= null;
						String query="select * from utenti where reg_status='pending'";
						pSt = conn.prepareStatement(query);	
						rs=pSt.executeQuery();
						if(rs.next()){
							%>
				<h2>Questi utenti richiedono l'abilitazione</h2>
				<form action="index.jsp" method="post">
					<table>
						<tr>
							<td>Nome</td>
							<td>Cognome</td>
							<td>Azienda</td>
							<td>Email</td>
							<td>Accetta</td>
							<td>Rifiuta</td>
						</tr>
						<%
								rs.previous();
							
							while(rs.next()){
								%>
						<tr>
							<td><%=rs.getString("nome") %></td>
							<td><%=rs.getString("cognome") %></td>
							<td><%=rs.getString("azienda") %></td>
							<td><%=rs.getString("email") %></td>
							<td><input type="radio"
								name="status<%=rs.getString("userId") %>" value="accept"
								checked="checked"></td>
							<td><input type="radio"
								name="status<%=rs.getString("userId") %>" value="refuse"></td>
						</tr>
						<%
							}
							%>
						<tr>
							<td><input type="hidden" name="submitted" value="true">
								<input type="submit" value="Invia"></td>
						</tr>
					</table>
				</form> <%
						}
					} catch (Exception e){
						e.printStackTrace();
					}
				}
			}
			
		
		//Se il login fallisce visualizzo il form di login con il messaggio di errore
		}
		%> <BR> <BR> <BR> <BR> <BR> <BR> <BR>
				<BR> <BR> <BR> <BR> <BR> <BR></td>
		</tr>
	</table>

</body>
</html>